package role

import (
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"goAdminV1/internal/middleware"
	"goAdminV1/internal/model"
	"goAdminV1/internal/model/entity"
	"goAdminV1/utility"
	"time"

	"goAdminV1/api/role/v1"
)

func (c *ControllerV1) RoleCreate(ctx context.Context, req *v1.RoleCreateReq) (res *v1.RoleCreateRes, err error) {
	// 检查角色标识是否已存在
	exists, err := model.ExistsByIdentify(ctx, req.Identify)
	if err != nil {
		return nil, utility.Error(utility.CodeOperation, err)
	}
	if exists {
		return nil, utility.Error(utility.CodeOperation, gerror.New("角色标识已存在"))
	}
	now := time.Now().Unix()
	// 获取用户ID
	userIDValue := ctx.Value(middleware.ContextUserIDKey)
	userID, ok := userIDValue.(uint)
	if !ok {
		return nil, utility.Error(utility.CodeOperation, gerror.New("从上下文中获取的用户 ID 类型错误"))
	}

	// 创建角色实体
	role := entity.CaRoles{
		RoleName:    req.RoleName,
		ParentId:    req.ParentId,
		Identify:    req.Identify,
		Description: req.Description,
		DataRange:   req.DataRange,
		CreatedAt:   uint(now),
		UpdatedAt:   uint(now),
		CreatorId:   userID,
	}

	// 插入角色数据
	roleId, err := model.CreateRole(ctx, role)
	if err != nil {
		return nil, utility.Error(utility.CodeOperation, err)
	}

	// 关联权限
	if len(req.Permissions) > 0 {
		if err := model.InsertRolePermissions(ctx, roleId, req.Permissions); err != nil {
			return nil, utility.Error(utility.CodeOperation, err)
		}
	}

	// 返回成功响应
	return &v1.RoleCreateRes{
		RoleId:  roleId,
		Message: "角色创建成功",
	}, nil
}
